
/**
 * Alibaba.com.cn Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package com.starlink.common.strategy.starorder;

import com.alibaba.fastjson.JSONObject;
import com.starlink.common.annotation.client.WeixinJsClient;
import com.starlink.common.annotation.client.weixin.UserPurchaseRes;
import com.starlink.common.annotation.client.weixin.WeixinJsCreateOrderReq;
import com.starlink.common.annotation.client.weixin.WeixinJsCreateOrderRes;
import com.starlink.common.domain.BaseEntity;
import com.starlink.common.domain.BaseVO;
import com.starlink.common.enums.OrderTypeEnum;
import com.starlink.common.enums.StarTypeEnum;
import com.starlink.common.strategy.IStarOrder;
import com.starlink.common.utils.AssertUtil;
import com.starlink.context.SessionContext;
import com.starlink.model.domain.OtherOrderDO;
import com.starlink.model.request.mall.WechatPay;
import com.starlink.model.request.other.StarOrderSubmitRequest;
import com.starlink.model.vo.StarTravelVO;
import com.starlink.service.OtherOrderService;
import com.starlink.service.StarTravelService;
import com.starlink.utils.OrderNumUtil;
import com.starlink.utils.OrderTimeOutUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zhanghong
 * @version StarTravelOrderPay.java, v 0.1 2024/4/25 23:41 下午 StarTravelOrderPay Exp $$
 */
@Component
public class StarTravelOrder implements IStarOrder {
    @Autowired
    private OtherOrderService otherOrderService;
    @Autowired
    private WeixinJsClient weixinJsClient;
    @Autowired
    private StarTravelService starTravelService;

    @Override
    public boolean supports(StarTypeEnum starTypeEnum) {
        return StarTypeEnum.STAR_TRAVEL.equals(starTypeEnum);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserPurchaseRes prePayment(StarOrderSubmitRequest request) {
        // 写入订单信息
        OtherOrderDO order = null;
        StarTravelVO starGoods = null;
        if (request.getOrderId() != null) {
            order = otherOrderService.lambdaQuery().eq(BaseEntity::getId, request.getOrderId()).one();
            AssertUtil.assertNotNull(order, "订单不存在");
            AssertUtil.assertNotNull(starTravelService.getByKey(order.getBizId()), "商品不存在");
        } else {
            AssertUtil.assertNotNull(request.getStarId(), "商品id不能为空");
            starGoods = starTravelService.getByKey(request.getStarId());
            // 写入订单信息
            order = new OtherOrderDO();
            order.setOrderNo(OrderNumUtil.createUniqueOrderNum());
            order.setStarType(StarTypeEnum.STAR_TRAVEL.getType());
            order.setPurchaseNum(request.getBuyNum());
            order.setBizId(request.getStarId());
            order.setOrderMoney(request.getPayMoney());
            order.setOrderStatus(1);
            if (starGoods.getFree() == 1) {
                order.setOrderStatus(2);
            } else {
                order.setOrderStatus(1);
            }
            order.setOpenId(request.getOpenId());
            order.setUserId(SessionContext.getWechatUserId());
            order.setTimeout(OrderTimeOutUtil.getTimeOutTime());
            order.setAddressId(request.getAddressId());
            otherOrderService.save(order);
        }

        //创建微信预订单
        UserPurchaseRes vipRes = new UserPurchaseRes();
        vipRes.setOrderId(order.getId());
        vipRes.setOrderType(StarTypeEnum.STAR_NURTURING.getType());
        if (order.getOrderStatus() == 2) {
            // 在支付时订单状态为2-已支付时直接返回（表示当前是免费订单或者0元订单）
            return vipRes;
        }

        WechatPay wechatPay = new WechatPay();
        wechatPay.setOrderId(String.valueOf(order.getId()));
        wechatPay.setOrderType(OrderTypeEnum.STAR.getType());
        String attach = JSONObject.toJSONString(wechatPay);
        WeixinJsCreateOrderReq req = new WeixinJsCreateOrderReq(order.getId(), order.getOrderMoney().doubleValue(), attach, request.getOpenId(), "星辅育");
        try {
            WeixinJsCreateOrderRes res = weixinJsClient.createOrder(req);
            weixinJsClient.buildPayRes(vipRes, res.getPrepay_id());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("微信下单失败!");
        }
        return vipRes;
    }

    @Override
    public BaseVO getBizInfo(Long bizId) {
        return starTravelService.getByKey(bizId);
    }
}
